from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage, InvalidPage
from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import render

# Create your views here.
from ScenicSpot.models import Img, TourName
from User.models import TourUser, LikeTour, com

# 登录
from tour import settings


def login(request):
    '''
    登录
    :param request:
    :return:
    '''
    if request.method == 'GET':
        if request.session.get('user'):
            return HttpResponseRedirect('/')
    elif request.method == 'POST':
        username = request.POST['uphone']
        password = request.POST['upwd']

        try:
            user = TourUser.objects.get(uphone=username)
        except Exception as e:
            return HttpResponse('用户名或密码有误')

        if password != user.upwd:
            return HttpResponse('用户名或密码有误')

        request.session['username'] = username
        return HttpResponseRedirect('/')
    return render(request, 'user/index.html')

# 退出
def out(request):
    '''
    退出
    :param request:
    :return:
    '''
    if 'username' in request.session:
        # 删除session
        del request.session['username']
        return HttpResponseRedirect('/')

# 注册
def reg(request):
    '''
    注册
    :param request:
    :return:
    '''
    if request.method == 'GET':
        return render(request, 'user/reg.html')
    elif request.method == 'POST':
        # 获取电话号码
        uphone = request.POST['uphone']
        if len(uphone) != 11:
            return HttpResponse('电话错误')
        # 获取昵称
        uname = request.POST['uname']
        # 获取密码
        password1 = request.POST['upwd']
        password2 = request.POST['upwd2']
        # 获取头像
        uimg = request.FILES['pic']
        # 保存头像
        fname = '%s/%s' % (settings.MEDIA_ROOT, uimg.name)
        picname = fname.split(".")[0] + ".png"
        with open(picname, 'wb') as pic:
            for c in uimg.chunks():
                pic.write(c)
        print("picture OK", picname)
        # 头像地址
        post_pic = str(picname.split("/")[1])
        # 验证密码是否相同
        if password1 != password2:
            return HttpResponse('两次密码不一致')
        # 验证手机号是否注册
        old_uname = TourUser.objects.filter(uphone=uphone)
        if old_uname:
            return HttpResponse('账号已经注册')
        # 保存数据
        try:
            TourUser.objects.create(
                uname=uname,
                uphone=uphone,
                upwd=password2,
                uphoto=post_pic,
            )
        except Exception as e:
            return HttpResponse("账号已经被注册")
        return HttpResponseRedirect('/login')
    return render(request, 'user/reg.html')


def home(request):
    '''
    个人中心
    :param request:
    :return:
    '''
    session = request.session.get('username')
    usermessage = TourUser.objects.filter(uphone=session)
    if session:
        pass
    else:
        return HttpResponseRedirect('/')
    b = ''
    for sex in usermessage:
        if int(sex.usex) == 0:
            b = '男'
        elif int(sex.usex) == 1:
            b = '女'
        else:
            b = '隐私'
    # 获取用户信息
    img = Img.objects.all().order_by('-id')[0:1]

    like = LikeTour.objects.filter(uphone=session)
    ulike = []
    for a in like:
        ulike.append(TourName.objects.get(id=a.tid_id))
    paginator = Paginator(ulike, 6)
    try:
        page_number = request.GET.get('page', '1')
        page = paginator.page(page_number)
    except (PageNotAnInteger, EmptyPage, InvalidPage):
        # 如果出现上述异常，默认展示第1页
        page = paginator.page(1)

    return render(request, 'user/home.html', locals())


def set(request,xq):
    '''
    修改信息
    :param request:
    :param xq:
    :return:
    '''
    uname = request.session.get('username')
    if uname:
        pass
    else:
        return HttpResponseRedirect('/login')
    user = TourUser.objects.filter(uphone=uname)
    b = ''
    for sex in user:
        if int(sex.usex) == 0:
            b = '男'
        elif int(sex.usex) == 1:
            b = '女'
        else:
            b = '隐私'

    if request.method == 'GET':
        return render(request,'user/home.html',locals())
    elif request.method == 'POST':
        # 获取电话号码
        nuname = request.POST['uname']
        nusex = request.POST['usex']
        nuage = request.POST['uage']
        if nuname and nusex and nuage and request.FILES['pic']:
            uimg = request.FILES['pic']
            # 保存头像
            fname = '%s/%s' % (settings.MEDIA_ROOT, uimg.name)
            picname = fname.split(".")[0] + ".png"
            with open(picname, 'wb') as pic:
                for c in uimg.chunks():
                    pic.write(c)
            print("picture OK", picname)
            # 头像地址
            post_pic = str(picname.split("/")[1])


            new = TourUser.objects.get(id=xq)
            new.uname = nuname
            new.usex = nusex
            new.uage = int(nuage)
            new.uphoto = post_pic
            new.save()
            return HttpResponseRedirect('/home')
        else:
            return HttpResponse("信息不全")


def comment(request,xq):
    '''
    评论
    :param request:
    :param xq:
    :return:
    '''
    session = request.session.get('username')
    user = TourUser.objects.get(uphone=session)
    text = request.POST['text']

    com.objects.create(
        text=text,
        about_id=xq,
        user_id=user.id
    )

    return HttpResponseRedirect('/read/%s'%xq)